<template>
  <div class="app-container">
    <div class="top">
      <el-input
        v-model="kwInput"
        placeholder="输入 关键词 进行筛选"
        class="input-with-select"
        clearable
        @keyup.native.enter="handleSearch"
      >
        <el-select
          slot="prepend"
          v-model="selected_project"
          v-loading="projectsLoading"
          placeholder="项目"
          clearable
        >
          <el-option
            v-for="item in projects"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>

        <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        :disabled="listLoading"
        @click="handleAction('create', '添加关键词挖掘')"
      >添加关键词挖掘
      </el-button>
    </div>

    <div style="float: right; margin-bottom: 10px; margin-right: 10px">
      <el-button
        size="mini"
        type="warning"
        title="点击跳转到修改规则页面"
        @click="handleAddRule(false)"
      >修改规则</el-button>
    </div>
    <el-table
      v-loading.body="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="handleSort"
    >

      <el-table-column align="center" width="100" prop="id" label="id" sortable="custom" />

      <el-table-column align="center" label="关键词">
        <template slot-scope="scope">
          <span title="查看详情" class="mt-detail" @click="handleViewDetail(scope.row.id)">{{ scope.row.input }}</span>
          <span :title="'Google 搜索 ' + scope.row.input">
            <svg-icon
              icon-class="google_search"
              @click.native="handleGoogle('https://www.google.com/search?source=hp&ei=&q='+ scope.row.input)"
            />
          </span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="当前结果数量" prop="result_count" />

      <el-table-column align="center" label="对应项目">
        <template slot-scope="scope">
          <el-tag>
            {{ scope.row.project__name }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="更新时间" prop="update_at" width="180" sortable="custom">
        <template slot-scope="scope">
          <span>{{ scope.row.update_at }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleAction('refresh', scope.row)">强制更新</el-button>
          <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <el-dialog
      class="mt-dialog"
      :title="title"
      :width="width"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="80px">
        <el-form-item v-if="action !== 'delete'" label="主关键词">
          <el-input v-model="temp.input" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="项目" class="mt-form">
          <el-select v-model="temp.project" placeholder="项目" clearable filterable>
            <el-option
              v-for="item in projects"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-alert
          v-if="action !== 'delete'"
          title="主关键词会单独进行搜索, {} 会被 主关键词 替换，再次进行搜索"
          type="warning"
          center
          show-icon
        />
        <br>
        <el-form-item v-if="action !== 'delete'" label="规则">
          <el-transfer
            v-model="temp.rules"
            filterable
            :filter-method="filterMethod"
            :titles="['可选规则', '已选规则']"
            filter-placeholder="输入搜索"
            :data="rules"
            :props="{
              key: 'id',
              label: 'rule'
            }"
          />
          <div style="margin-top: 10px;float: right">
            <el-button size="mini" @click="handleFetchRules">刷新</el-button>
            <el-button type="warning" size="mini" @click="handleAddRule(1)">修改规则</el-button>
          </div>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { Get, Post, Put, Delete, Refresh } from '@/api/spider/top_content/seed'
import { Get as GetProjects } from '@/api/erp/elicink/project'
import { Get as GetRules } from '@/api/spider/top_content/rule'

import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  data() {
    return {
      data: [],
      listLoading: true,
      projects: [],
      selected_project: null,
      rules: [],
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        input: '',
        project: null,
        rules: []
      },
      width: '50%',

      projectsLoading: false
    }
  },
  created() {
    this.getList()
    this.handleFetchProjects()
    this.handleFetchRules()
  },
  methods: {
    resetTemp() {
      this.temp = {
        input: '',
        project: null,
        rules: []
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc,
        project_id: this.selected_project
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = row
          this.resetTemp()
          this.dialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.input}?`
          this.temp = row
          this.dialogVisible = true
          break
        case 'refresh':
          Refresh(row.id)
            .then(response => {
              this.$notify({
                title: '成功',
                message: '刷新成功，载入数据中!',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
            .catch(e => {
            })
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post({
            input: _data.input,
            project: _data.project,
            rules: _data.rules
          }).then(response => {
            this.dialogVisible = false
            this.getList()
            this.notify('添加成功')
          })
          return
        case 'delete':
          Delete(_data.id).then((response) => {
            this.dialogVisible = false
            this.getList()
            this.notify('删除成功')
          })
          return
        case 'edit':
          Put(_data.id, {
            name: _data.name,
            text: _data.text,
            websites: _data.websites
          }).then((response) => {
            this.dialogVisible = false
            this.getList()
            this.notify('更新成功')
          })
          return
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    filterMethod(query, item) {
      return item.rule.indexOf(query) > -1
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    handleGoogle(link) {
      window.open(link)
    },
    handleViewDetail(v) {
      this.$router.push({ name: 'top_content.detail', params: { seed_id: v }})
    },
    handleFetchProjects() {
      this.projectsLoading = true
      GetProjects()
        .then(response => {
          this.projectsLoading = false
          this.projects = response.data.data
        })
        .catch(e => {
          this.projectsLoading = false
        })
    },
    handleAddRule(v) {
      if (v) {
        const link = this.$router.resolve({
          path: '/spider/top_content/rule'
        })
        window.open(link.href)
      } else {
        this.$router.push({ path: '/spider/top_content/rule' })
      }
    },
    handleFetchRules() {
      GetRules().then(response => {
        this.rules = response.data.data
      })
    },
    scrollTop() {
      window.scrollTo(0, 0)
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-select .el-input {
    width: 350px;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .mt-detail {
    text-decoration: underline;
    margin-right: 8px;
    color: #409EFF;
  }

  .mt-detail:hover, .svg-icon:hover {
    cursor: pointer;
  }

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-form >>> .el-select {
    width: 100%;
  }

  .mt-form >>> .el-input__inner {
    width: 100%;
  }

  .mt-dialog >>> .el-dialog {
    margin: 88px auto !important;
  }
</style>
